import {
  Component,
  OnInit,
  ChangeDetectionStrategy,
  Input,
  forwardRef,
} from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import { CheckboxComponent } from './checkbox.component';
export type CheckboxValue = any;
@Component({
  selector: 'app-check-group',
  template: `
    <div class="xm-check-group">
      <ng-content></ng-content>
    </div>
  `,
  styles: [
    `
      .app-check-group {
        display: inline-block;
      }
    `,
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => CheckGroupComponent),
      multi: true,
    },
  ],
})
export class CheckGroupComponent implements OnInit, ControlValueAccessor {
  private checkboxs: CheckboxComponent[] = [];
  current: CheckboxValue[] = []; 
  constructor() {}

  ngOnInit(): void {}
  handleCheckboxClick(value: CheckboxValue, check: boolean): void {
    let newCurrent = this.current.slice();
    if (check) {
      if (!newCurrent.includes(value)) {
        newCurrent.push(value);
      }
    } else {
      const targetIndex = newCurrent.findIndex((item) => item === value);
      console.log(targetIndex)
      if (targetIndex > -1) {
        newCurrent.splice(targetIndex, 1);
      }
    }
    this.writeValue(newCurrent);
  }
  private onChange = (value: CheckboxValue[]) => {};
  private onTouched = () => {};
  writeValue(value: CheckboxValue[]): void {
    if (value) {
      this.updataCheckBox(value);
    }
  }
  registerOnChange(fn: (value: CheckboxValue[]) => void): void {
    this.onChange = fn;
  }
  registerOnTouched(fn: () => void): void {
    this.onTouched = fn;
  }
  addCheckbox(checkbox: CheckboxComponent) {
    this.checkboxs.push(checkbox); 
  }
  updataCheckBox(current: CheckboxValue[]) {
    if (this.checkboxs.length) {
      this.checkboxs.forEach((item) => { 
        item.writeValue(current.includes(item.value));
      });
      this.current = current;
      this.onChange(this.current);
    }
  }
}
